#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>

sem_t *sem;
char message[100] ={0};
void *read_func(void *arg)
{   
    printf("read thread start\n");
    sem_wait(sem);//等待信号量
    printf("read message: %s\n", message);
}

void *write_func(void *arg)
{
     printf("write thread start\n");
    sleep(1);
    strcpy(message, "hello world");
    sem_post(sem);//释放信号量

}

int main(int argc, char const *argv[])
{   // 开辟两个线程 一个负责读 一个负责写 
    pthread_t read_tt, write_tt;
    printf(" start int sem addr ");
     sem = malloc(sizeof(sem_t)); // 开辟内存空间
    sem_init(sem, 0, 0); //  0 线程共享 初始化值为0
    printf("sem addr: %p\n", sem);

    pthread_create(&read_tt, NULL,  read_func, NULL);
    pthread_create(&write_tt, NULL,  write_func, NULL);

    pthread_join(read_tt, NULL);
    pthread_join(write_tt, NULL);
     
    return 0;
}
